function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useEffect, useMemo } from 'react';
import { emptyFn, util } from "../util";
export function useKeyDown(elRef, deps) {
  var _deps = _slicedToArray(deps, 4),
    table = _deps[0],
    editableColumnIndex = _deps[1],
    maxRowIndex = _deps[2],
    editable = _deps[3];
  var _table$generateColumn = table.generateColumns(),
    allColumns = _table$generateColumn.allColumns;
  var listenerOnDocument = table.props.listenerOnDocument;
  var cb = useMemo(function () {
    if (!editable) {
      return emptyFn;
    }
    var startEditing = function startEditing(_ref, _ref2) {
      var rowIndex = _ref.rowIndex,
        columnIndex = _ref.columnIndex;
      var keyCode = _ref2.keyCode;
      return table.startEditing({
        rowIndex: rowIndex,
        dataIndex: allColumns[columnIndex].dataIndex
      }, {
        keyCode: keyCode
      });
    };
    var getNextEditColumnIndex = function getNextEditColumnIndex(columnIndex) {
      var _editableColumnIndex$;
      return (_editableColumnIndex$ = editableColumnIndex.find(function (c) {
        return c > columnIndex;
      })) !== null && _editableColumnIndex$ !== void 0 ? _editableColumnIndex$ : columnIndex;
    };
    var getPrevEditColumnIndex = function getPrevEditColumnIndex(columnIndex) {
      var arr = editableColumnIndex.filter(function (c) {
        return c < columnIndex;
      });
      return arr.length > 0 ? arr[arr.length - 1] : Math.max(columnIndex, 0);
    };
    var minColumnIndex = editableColumnIndex[0] || 0;
    var maxColumnIndex = editableColumnIndex[editableColumnIndex.length - 1];
    var addRow = function addRow(rowIndex, columnIndex, _ref3) {
      var keyCode = _ref3.keyCode;
      var autoAddRow = table.props.keyBoardToAddRow;
      if (autoAddRow && rowIndex >= maxRowIndex) {
        table.addRows().then(function () {
          startEditing({
            rowIndex: rowIndex + 1,
            columnIndex: columnIndex
          }, {
            keyCode: keyCode
          });
        });
        return true;
      }
      return false;
    };
    return function (e) {
      var _table$props$onBefore, _table$props, _table$props$onAfterE, _table$props2;
      var _table$state$selected = table.state.selected,
        rowIndex = _table$state$selected.rowIndex,
        dataIndex = _table$state$selected.dataIndex,
        editing = _table$state$selected.editing;
      var el = document.activeElement || {};
      var disabled = table.props.disabled;
      if (disabled === false) return;
      if (el.tagName !== 'BODY' && !util.closest(e.target, function (dom) {
        return dom === elRef.current;
      })) {
        // 焦点在其他容器内部
        return;
      }
      var columnIndex = allColumns.findIndex(function (c) {
        return c.dataIndex === dataIndex;
      });
      var shiftKey = e.shiftKey,
        ctrlKey = e.ctrlKey;
      if (shiftKey && e.keyCode === 16) {
        // 仅按下shift键，直接返回
        return;
      }
      if (editing && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA')) {
        if (shiftKey && el.tagName === 'TEXTAREA' && e.keyCode === 13) {
          // shift + enter 直接返回，执行textarea默认行为
          return;
        }
        var start = util.getCursorPosition();
        var end = util.getSelectionEnd();
        if ([37, 39].indexOf(e.keyCode) > -1) {
          var _el$value;
          if (start !== end) {
            util.setCursorPosition(el, 37 === e.keyCode ? start : end);
            return;
          }
          if (start > 0 && 37 === e.keyCode || start > -1 && start < ((_el$value = el.value) === null || _el$value === void 0 ? void 0 : _el$value.length) && 39 === e.keyCode) {
            return;
          }
        }
      }
      if (((_table$props$onBefore = (_table$props = table.props).onBeforeEditCellKeyDown) === null || _table$props$onBefore === void 0 ? void 0 : _table$props$onBefore.call(_table$props, e, {
        rowIndex: rowIndex,
        columnIndex: columnIndex
      })) === false) {
        return;
      }
      var retValue = false;
      switch (e.keyCode) {
        case 9: // tab
        case 13:
          // enter
          if (shiftKey && e.keyCode === 9) {
            // shift+tab
            if (rowIndex === -1 || columnIndex === -1) {
              // 没有选中，则选中末行的最后一个编辑单元格
              retValue = startEditing({
                rowIndex: maxRowIndex,
                columnIndex: maxColumnIndex
              }, e);
            } else if (columnIndex === minColumnIndex) {
              // 当前选中在第一个编辑列，跳转到上一行的最后一个编辑单元格
              retValue = rowIndex > 0 ? startEditing({
                rowIndex: rowIndex - 1,
                columnIndex: maxColumnIndex
              }, e) : true;
            } else {
              // 移动到前一个编辑单元格
              retValue = startEditing({
                rowIndex: rowIndex,
                columnIndex: getPrevEditColumnIndex(columnIndex)
              }, e);
            }
          } else {
            if (rowIndex === -1 || columnIndex === -1) {
              // 没有选中，则选中第一行的第一个编辑单元格
              retValue = startEditing({
                rowIndex: 0,
                columnIndex: minColumnIndex
              }, e);
            } else if (columnIndex === maxColumnIndex) {
              // 当前选中已经到最后一列，跳转到下一行的第一个编辑单元格
              if (rowIndex < maxRowIndex) {
                retValue = startEditing({
                  rowIndex: rowIndex + 1,
                  columnIndex: minColumnIndex
                }, e);
              } else {
                retValue = addRow(rowIndex, minColumnIndex, e);
              }
            } else {
              // 移动到后一个编辑单元格
              retValue = startEditing({
                rowIndex: rowIndex,
                columnIndex: getNextEditColumnIndex(columnIndex)
              }, e);
            }
          }
          break;
        case 35:
          // end
          retValue = startEditing({
            rowIndex: maxRowIndex,
            columnIndex: Math.max(minColumnIndex, columnIndex)
          }, e);
          break;
        case 36:
          // home
          retValue = startEditing({
            rowIndex: 0,
            columnIndex: Math.max(minColumnIndex, columnIndex)
          }, e);
          break;
        case 37:
          // left
          retValue = startEditing({
            rowIndex: Math.max(0, rowIndex),
            columnIndex: getPrevEditColumnIndex(columnIndex)
          }, e);
          break;
        case 38:
          // up
          retValue = startEditing({
            rowIndex: Math.max(0, rowIndex - 1),
            columnIndex: Math.max(minColumnIndex, columnIndex)
          }, e);
          break;
        case 39:
          // right
          retValue = startEditing({
            rowIndex: Math.max(0, rowIndex),
            columnIndex: getNextEditColumnIndex(columnIndex)
          }, e);
          break;
        case 40:
          // down
          if (rowIndex < maxRowIndex) {
            retValue = startEditing({
              rowIndex: rowIndex + 1,
              columnIndex: Math.max(minColumnIndex, columnIndex)
            }, e);
          } else {
            retValue = addRow(rowIndex, Math.max(minColumnIndex, columnIndex), e);
          }
          break;
        default:
          break;
      }
      if (retValue) {
        var _elRef$current;
        (_elRef$current = elRef.current) === null || _elRef$current === void 0 || _elRef$current.focus();
        e.preventDefault();
        e.stopPropagation();
      } else {
        table.notify(e.keyCode, 'keyboardEvent').then();
      }
      (_table$props$onAfterE = (_table$props2 = table.props).onAfterEditCellKeyDown) === null || _table$props$onAfterE === void 0 || _table$props$onAfterE.call(_table$props2, e, {
        rowIndex: rowIndex,
        columnIndex: columnIndex
      });
    };
  }, deps);
  useEffect(function () {
    if (listenerOnDocument && editable) {
      document.addEventListener('keydown', cb);
      return function () {
        document.removeEventListener('keydown', cb);
      };
    }
  }, [cb, listenerOnDocument, editable]);
  return listenerOnDocument || !editable ? null : cb;
}